/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AddPanel.java
 *
 * Created on Mar 1, 2013, 1:17:30 PM
 */
package edu.ncsu.csc573.project1.gui;

import edu.ncsu.csc573.project1.peer.Peer;
import edu.ncsu.csc573.project1.util.Rfc;
import java.io.File;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author user
 */
public class AddPanel extends javax.swing.JPanel {

    Peer peer;
    /** Creates new form AddPanel */
    public AddPanel(Peer peer) {
        this.peer = peer;
        initComponents();
        rfcTableModel = (DefaultTableModel) this.rfcTable.getModel();
        Iterator it = peer.getRfcMap().entrySet().iterator();
         
        rfcTableModel.getDataVector().removeAllElements();
        String registeredStatus = "";

        if (peer.isConnected()) {
            registeredStatus = "Yes";
        } else {
            registeredStatus = "No";
        }
        
        while (it.hasNext()) {
            Map.Entry<Integer, Rfc> pair = (Map.Entry<Integer, Rfc>) it.next();
            rfcTableModel.addRow(new Object[]{pair.getKey(), pair.getValue().getMetaData().getName(), registeredStatus});
        }
    }
    
    public void setRegisteredStatus(String status) {
        for (int i = 0; i < rfcTableModel.getRowCount(); ++i) {
            rfcTableModel.setValueAt("Yes", i, 2);
        }
    }
    
    public AddPanel(LinkedList<Rfc> registeredRfcList) {
        initComponents();
        rfcTableModel = (DefaultTableModel) this.rfcTable.getModel();
        for (int i = 0; i < registeredRfcList.size(); ++i) {
            rfcTableModel.addRow(new Object[]{registeredRfcList.get(i).getMetaData().getNumber(),
                                              registeredRfcList.get(i).getMetaData().getName(),
                                              "Yes"});
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        rfcTable = new javax.swing.JTable() {
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        rfcNumberField = new javax.swing.JTextField();
        rfcTitleField = new javax.swing.JTextField();
        rfcLocationField = new javax.swing.JTextField();
        browseButton = new javax.swing.JButton();
        uploadButton = new javax.swing.JButton();

        rfcTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null}
            },
            new String [] {
                "RFC Number", "RFC Title", "Registered with Server"
            }
        ));
        jScrollPane1.setViewportView(rfcTable);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("New RFC Information"));

        jLabel1.setText("RFC Number :");

        jLabel2.setText("RFC Title :");

        jLabel3.setText("Location :");

        rfcNumberField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rfcNumberFieldActionPerformed(evt);
            }
        });

        browseButton.setText("Browse");
        browseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rfcNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(rfcTitleField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(rfcLocationField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(browseButton))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(rfcNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rfcTitleField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rfcLocationField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(browseButton))
                .addContainerGap())
        );

        uploadButton.setText("Send to Server");
        uploadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uploadButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(uploadButton, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(117, 117, 117)
                        .addComponent(uploadButton, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(20, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void uploadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uploadButtonActionPerformed
        // TODO add your handling code here:
        if (this.rfcNumberField.getText().equals("")) {
            JOptionPane.showMessageDialog(new JFrame(), "RFC must have a number.", "Add Error", JOptionPane.ERROR_MESSAGE);
            return;
        } else if (this.rfcTitleField.getText().equals("")) {
            JOptionPane.showMessageDialog(new JFrame(), "RFC must have a title.", "Add Error", JOptionPane.ERROR_MESSAGE);
            return;
        } else if (this.rfcLocationField.getText().equals("")) {
            JOptionPane.showMessageDialog(new JFrame(), "Please specify RFC location.", "Add Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int rfcNumber = Integer.parseInt(this.rfcNumberField.getText());
        String rfcTitle = this.rfcTitleField.getText();
        File fileToUpload = new File(this.rfcLocationField.getText());
        if (! fileToUpload.exists()) {
            JOptionPane.showMessageDialog(new JFrame(), "No RFC found at specified location.", "Add Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        boolean retVal = peer.addRfc(rfcNumber, rfcTitle, fileToUpload);   
        if (retVal) {
            rfcTableModel = (DefaultTableModel) this.rfcTable.getModel();
            rfcTableModel.addRow(new Object[]{new Integer(rfcNumber), rfcTitle, "Yes"});        
        } else {
            JOptionPane.showMessageDialog(new JFrame(), "RFC already exists in the peer's database.", "Add Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_uploadButtonActionPerformed

    private void rfcNumberFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rfcNumberFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_rfcNumberFieldActionPerformed

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
        // TODO add your handling code here:
        final JFileChooser fc = new JFileChooser();
        fc.setMultiSelectionEnabled(false);
        fc.setAcceptAllFileFilterUsed(false);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
        fc.setFileFilter(filter);
        
        int returnVal = fc.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            System.out.println("File chosen : " + file.getAbsolutePath());
            this.rfcLocationField.setText(file.getAbsolutePath());
        }
    }//GEN-LAST:event_browseButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton browseButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField rfcLocationField;
    private javax.swing.JTextField rfcNumberField;
    private javax.swing.JTable rfcTable;
    private javax.swing.JTextField rfcTitleField;
    private javax.swing.JButton uploadButton;
    // End of variables declaration//GEN-END:variables
    private javax.swing.table.DefaultTableModel rfcTableModel;
}
